package org.jeecg.modules.flowable.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.flowable.ui.common.properties.FlowableCommonAppProperties;
import org.flowable.ui.common.security.CustomPersistentRememberMeServices;
import org.flowable.ui.common.security.PersistentTokenService;
import org.flowable.ui.common.tenant.TenantProvider;
import org.flowable.ui.modeler.service.FlowableModelQueryService;
import org.flowable.ui.modeler.service.ModelImageService;
import org.flowable.ui.modeler.service.ModelServiceImpl;
import org.flowable.ui.modeler.serviceapi.ModelService;
import org.jeecg.modules.flowable.converter.CustomBpmnJsonConverter;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.RememberMeServices;

/**
 * 流程模型配置
 */
@Configuration
@ComponentScan(
        value = {
                "org.flowable.ui.modeler.repository",
                "org.flowable.ui.common.repository"
        })
public class ModelerBeanConfig {

    @Bean(destroyMethod = "clearCache")
    @Qualifier("flowableModeler")
    public SqlSessionTemplate modelerSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public CustomBpmnJsonConverter createCustomBpmnJsonConverter() {
        return new CustomBpmnJsonConverter();
    }

    @Bean
    public ModelService createModelService() {
        return new ModelServiceImpl();
    }

    @Bean
    public ModelImageService createModelImageService() {
        return new ModelImageService();
    }

    @Bean
    public FlowableModelQueryService createFlowableModelQueryService() {
        return new FlowableModelQueryService();
    }

    @Bean
    public TenantProvider myTenantProvider() {
        return () -> null;
    }

    @Bean
    @ConditionalOnMissingBean
    public RememberMeServices flowableUiRememberMeService(FlowableCommonAppProperties properties, UserDetailsService userDetailsService, PersistentTokenService persistentTokenService) {
        CustomPersistentRememberMeServices customPersistentRememberMeServices = new CustomPersistentRememberMeServices(properties, userDetailsService, persistentTokenService);
        customPersistentRememberMeServices.setCookieName("DRAGON_FLOW_REMEMBER_ME");
        return customPersistentRememberMeServices;
    }
}